/**
 * 公式的请求接口及相关方法
 * urlList  {funName: httpUrl}
 * 默认返回请求Promise对象
 * */

import store from '../../store';

const urlList = {
  getAuthList: 'system/api/auth_list', // 获取权限列表
  getUserInfo: 'system/api/member_info', // 获取用户信息
  login: 'login/api/login', // 用户登录
};

const apiList = {};

Object.keys(urlList).map(k => {
  // 使用function语法，使得调用时this能指向 http
  apiList[k] = function (params = {}, config = {}) {
    return this.$post(urlList[k], params, config);
  };
});

Object.assign(apiList, {
  /**
   * 自定义方法
   * */
  setMenuFromRule: function (limits = 1000) {
    let {rule, uid, routerList} = store.getters;
    // ...
    // return store.commit('setRouterList', rule);

    function setList(auth, lists) {
      lists = lists.map(listItem => {
        let list = {...listItem};
        if (list.children && list.children.length) {
          list.children = setList(auth, list.children);
        }
        if (auth.includes(list.path) || list.children && list.children.length) return list;
      });
      return lists.filter(e => e);
    }

    return this.getAuthList({uid, limits}).then(res => {
      // return this.$post('system/api/auth_list', {uid, limits}).then(res => {
      let rules = (res.list || []).map(e => (/^\//.test(e.auth_mca) ? '' : '/') + e.auth_mca);
      store.commit('setRouterList', setList(rules, [...rule]));
      store.commit('setRules', rules);
      return {
        routerList: store.state.routerList,
        rules: store.state.rules
      };
    });
  },

  dfGetList: function (url, params, that = {}, listKey = 'list', totalKey = 'total') {
    return this.$post(url, params).then(res => {
      that[listKey] = res.list;
      that[totalKey] = res.total;
      return res;
    });
  }
});

export default apiList;